import React, { useEffect, useState, useCallback } from 'react';
import { Select, notification } from 'antd';
import { fetchApi } from '../../general/api';

interface OptionType {
    value: number;
    label: string;
}

interface SelectProbeType {
    HostID?: number;
    PorjectID?: string; // 父级值，用于级联请求
    NotBound: string; // 下拉框类型
    value?: string; // 当前选中的值（由外部受控）
    onChange?: (value: string) => void; // 值变更时的回调
    placeholder?: string; // 占位符
    style?: React.CSSProperties; // 自定义样式
}

const SelectDynamicType: React.FC<SelectProbeType> = ({
    style,
    HostID,
    PorjectID = '',
    NotBound,
    value, // 从父组件传入的受控值
    onChange, // 从父组件传入的受控回调
    placeholder = '请选择',
}) => {
    const [options, setOptions] = useState<OptionType[]>([]); // 下拉选项
    const [loading, setLoading] = useState(false); // 加载状态

    const fetchOptions = useCallback(async () => {
        setLoading(true);
        try {
            const response = await fetchApi(
                `/easymonitor/api/probe?not_bound=${NotBound}&project_id=${PorjectID}&host_id=${HostID}`
            );
            const formattedOptions = Array.isArray(response)
                ? response.map((item: any) => ({
                    value: item.alarm_config_id,
                    label: item.alarm_config_name,
                }))
                : [];
            setOptions([{ value: 0, label: '全部' }, ...formattedOptions]);
        } catch (error) {
            notification.error({
                message: '请求失败',
                description: `获取数据失败: ${error}`,
                duration: 2,
            });
        } finally {
            setLoading(false);
        }
    }, [NotBound, PorjectID, HostID]);

    useEffect(() => {
        fetchOptions();
    }, [fetchOptions]);

    return (
        <Select
            style={style}
            showSearch
            loading={loading}
            placeholder={placeholder}
            value={value} // 受控值
            onChange={onChange} // 通知外部变化
            options={options}
            filterOption={(input, option) =>
                option?.label.toLowerCase().includes(input.toLowerCase()) || false
            }
        />
    );
};

export default SelectDynamicType;
